import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.Scanner;

/**
 * 持续调用API用于Frida Hook测试
 * 
 * 使用方法：
 * 1. javac ContinuousAPICall.java
 * 2. java ContinuousAPICall
 * 3. 在另一个终端: jps -l  (找到进程ID)
 * 4. frida -p <进程ID> -l hook_server_direct.js
 * 5. 回到程序，按Enter触发API调用
 * 6. 观察Frida输出
 */
public class ContinuousAPICall {
    
    private static final String API_URL = "http://120.27.155.222:9999/api/message/send-test";
    
    public static void main(String[] args) {
        System.out.println("=".repeat(100));
        System.out.println("📡 持续API调用测试 - 用于Frida Hook");
        System.out.println("=".repeat(100));
        System.out.println();
        
        System.out.println("📝 使用说明:");
        System.out.println("1. 保持此程序运行");
        System.out.println("2. 打开新终端，执行: jps -l");
        System.out.println("3. 找到此程序的进程ID（例如：12345 ContinuousAPICall）");
        System.out.println("4. 在新终端执行: frida -p 12345 -l hook_server_direct.js");
        System.out.println("5. 等待Frida显示'Hook设置完成'");
        System.out.println("6. 回到这里，按Enter键触发API调用");
        System.out.println("7. 观察Frida终端的输出");
        System.out.println();
        
        // 显示进程ID提示
        System.out.println("💡 提示：如果有jps命令，进程ID可能是：");
        System.out.println("   进程名：ContinuousAPICall");
        System.out.println();
        
        Scanner scanner = new Scanner(System.in);
        int callCount = 0;
        
        while (true) {
            System.out.println("-".repeat(100));
            System.out.print("按Enter键调用API（或输入'quit'退出）: ");
            String input = scanner.nextLine().trim();
            
            if (input.equalsIgnoreCase("quit") || input.equalsIgnoreCase("q")) {
                System.out.println("\n👋 再见！");
                break;
            }
            
            callCount++;
            System.out.println();
            System.out.println("🚀 [调用 #" + callCount + "] 正在调用API...");
            System.out.println("   URL: " + API_URL);
            
            try {
                HttpClient client = HttpClient.newHttpClient();
                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(API_URL))
                        .GET()
                        .build();
                
                long startTime = System.currentTimeMillis();
                HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
                long endTime = System.currentTimeMillis();
                
                System.out.println("   ✅ API调用成功！");
                System.out.println("   耗时: " + (endTime - startTime) + " ms");
                System.out.println("   状态码: " + response.statusCode());
                System.out.println();
                System.out.println("📄 API响应:");
                System.out.println("-".repeat(100));
                
                // 格式化JSON输出
                String jsonResponse = response.body();
                System.out.println(formatJson(jsonResponse));
                
                System.out.println("-".repeat(100));
                System.out.println();
                System.out.println("⚠️  现在检查Frida终端！");
                System.out.println("    如果Hook成功，应该能看到捕获的AES密钥！");
                System.out.println();
                
            } catch (Exception e) {
                System.out.println("   ❌ API调用失败: " + e.getMessage());
                e.printStackTrace();
                System.out.println();
            }
        }
        
        scanner.close();
    }
    
    /**
     * 简单的JSON格式化
     */
    private static String formatJson(String json) {
        // 移除首尾空白
        json = json.trim();
        
        // 如果不是JSON，直接返回
        if (!json.startsWith("{") && !json.startsWith("[")) {
            return json;
        }
        
        StringBuilder formatted = new StringBuilder();
        int indent = 0;
        boolean inString = false;
        
        for (int i = 0; i < json.length(); i++) {
            char c = json.charAt(i);
            
            // 处理字符串
            if (c == '"' && (i == 0 || json.charAt(i - 1) != '\\')) {
                inString = !inString;
                formatted.append(c);
                continue;
            }
            
            if (inString) {
                formatted.append(c);
                continue;
            }
            
            // 处理格式
            switch (c) {
                case '{':
                case '[':
                    formatted.append(c).append('\n');
                    indent++;
                    formatted.append("    ".repeat(indent));
                    break;
                case '}':
                case ']':
                    formatted.append('\n');
                    indent--;
                    formatted.append("    ".repeat(indent));
                    formatted.append(c);
                    break;
                case ',':
                    formatted.append(c).append('\n');
                    formatted.append("    ".repeat(indent));
                    break;
                case ':':
                    formatted.append(c).append(' ');
                    break;
                default:
                    if (!Character.isWhitespace(c)) {
                        formatted.append(c);
                    }
                    break;
            }
        }
        
        return formatted.toString();
    }
}


